
import { MBErrorCode } from './mb_constants';
import MBProtocalFactory from './mb_constants';
import MBCore from './mb_core'
import MBUtils from './mb_utils'
import MBSocketProvider from './mb_socket_provider'
import MBQoS4SendDaemon from './mb_daemon_qos_send'

class MBDataSender {
    sendLogin(loginInfo: any) {
        if (!MBSocketProvider.isLocalSocketReady()) {

            if (MBCore.debugEnabled())
                console.log("发送登陆指令时，socket连接未就绪，首先开始尝试发起连接（登陆指令将在连接成功后的回调中自动发出）。。。。")

            let that = this;
            let connectionDoneCallback = (sucess: any, extraObj: any) => {
                // 成功建立了Websocket连接后立即把登陆包发出去
                if (sucess)
                    that.sendLoginImpl(loginInfo);
                // TCP连接建立失败
                else
                    console.log("[来自ws连接结果回调观察者通知]socket连接失败，本次登陆信息未成功发出！");
            };
            // 调置连接回调
            MBSocketProvider.setConnectionDoneCallback(connectionDoneCallback);

            // 主要是为了触发 LocalUDPSocketProvider中的 tryConnectToHost()调用
            // ，connect完后将自动调用上方设置的回调，从而实现登陆指令在连接成功后的发送
            return MBSocketProvider.resetLocalSocket() != null
                ? MBErrorCode.COMMON_CODE_OK : MBErrorCode.BAD_CONNECT_TO_SERVER;
        }
        else {
            // 发送登陆指令
            return this.sendLoginImpl(loginInfo);
        }
    };

    sendLoginImpl(loginInfo: any) {
        // byte[] b = ProtocalFactory.createPLoginInfo(loginUserId, loginToken, extra).toBytes();

        let p = MBProtocalFactory.createPLoginInfo({ userid: loginInfo.loginUserId, loginInfo });
        let code = this.send(JSON.stringify(p));
        // 登陆信息成功发出时就把登陆名存下来
        if (code === 0) {
            MBCore.setCurrenetLoginInfo(loginInfo);
        }

        return code;
    };
    sendLoginout() {
        let code = MBErrorCode.COMMON_CODE_OK;
        if (MBCore.isLoginHasInit()) {
            let p = MBProtocalFactory.createPLoginoutInfo({ from: MBCore.getCurrentLoginInfo().loginUserId });
            code = this.send(JSON.stringify(p));
            if (code === 0) {
            }
        }
        MBCore.release();

        return code;
    };

    sendKeepAlive() {
        let p = MBProtocalFactory.createPKeepAlive({ from: MBCore.getCurrentLoginInfo().loginUserId });
        return this.send(JSON.stringify(p));
    };

    sendCommonData(p: any) {
        if (p) {
            // byte[] b = p.toBytes();
            let dataWithString = JSON.stringify(p);
            let code = this.send(dataWithString);
            if (code === 0) {
                // 【【C2C或C2S模式下的QoS机制1/4步：将包加入到发送QoS队列中】】
                // 如果需要进行QoS质量保证，则把它放入质量保证队列中供处理(已在存在于列
                // 表中就不用再加了，已经存在则意味当前发送的这个是重传包哦)
                if (p.QoS && !MBQoS4SendDaemon.exist(p.fp))
                    MBQoS4SendDaemon.put(p);
            }
            return code;
        }
        else
            return MBErrorCode.COMMON_INVALID_PROTOCAL;
    };

    send = function (dataWithString: any) {
        let websocket = MBSocketProvider.getLocalSocket();
        if (websocket != null && websocket.readyState === 1) {// && [ClientCoreSDK sharedInstance].connectedToServer)
            return MBUtils.send(websocket, dataWithString) ? MBErrorCode.COMMON_CODE_OK : MBErrorCode.COMMON_DATA_SEND_FAILD;
        }
        else {
            console.log("scocket未连接，无法发送，本条将被忽略（dataWithString=" + dataWithString + "）!");
            return MBErrorCode.COMMON_CODE_OK;
        }
    };
}

export default new MBDataSender();